using System.Xml;

namespace 道路运输从业人员无纸化考试系统
{
	public static class XMLHelper
	{
		public static string Read(string path, string node, string attribute)
		{
			string value = "";
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(path);
				XmlNode xn = doc.SelectSingleNode(node);
				value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
			}
			catch
			{
			}
			return value;
		}

        public static string Read(System.IO.Stream sm, string node, string attribute)
        {
            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(sm);
                XmlNode xn = doc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch
            {
            }
            return value;
        }

        public static void Insert(string path, string node, string element, string attribute, string value)
		{
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(path);
				XmlNode xn = doc.SelectSingleNode(node);
				if (element.Equals(""))
				{
					if (!attribute.Equals(""))
					{
						XmlElement xe2 = (XmlElement)xn;
						xe2.SetAttribute(attribute, value);
					}
				}
				else
				{
					XmlElement xe2 = doc.CreateElement(element);
					if (attribute.Equals(""))
					{
						xe2.InnerText = value;
					}
					else
					{
						xe2.SetAttribute(attribute, value);
					}
					xn.AppendChild(xe2);
				}
				doc.Save(path);
			}
			catch
			{
			}
		}

		public static void Update(string path, string node, string attribute, string value)
		{
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(path);
				XmlNode xn = doc.SelectSingleNode(node);
				XmlElement xe = (XmlElement)xn;
				if (attribute.Equals(""))
				{
					xe.InnerText = value;
				}
				else
				{
					xe.SetAttribute(attribute, value);
				}
				doc.Save(path);
			}
			catch
			{
			}
		}

		public static void Delete(string path, string node, string attribute)
		{
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(path);
				XmlNode xn = doc.SelectSingleNode(node);
				XmlElement xe = (XmlElement)xn;
				if (attribute.Equals(""))
				{
					xn.ParentNode.RemoveChild(xn);
				}
				else
				{
					xe.RemoveAttribute(attribute);
				}
				doc.Save(path);
			}
			catch
			{
			}
		}
	}
}
